<?php
class User_model extends CI_Model {

  public function __construct()
  {
    $this->load->database();
  }

  public function get_items($store_id)
  {
    $this->db->where('store_id', $store_id);
    $this->db->where('item_state', 1);
    $this->db->order_by('item_type', 'desc');
    $query = $this->db->get('item');
    return $query->result_array();
  }

  public function get_user($user_id)
  {
    $this->db->where('user_id', $user_id);
    $query = $this->db->get('user');
    return $query->row_array();
  }

  public function update_user($user_id)
  {
    $query = $this->get_user($user_id);
    $name = $this->input->post('name');
    $phone = $this->input->post('phone');
    $address = $this->input->post('address');
    $dorm = $this->input->post('dorm');
    $email = $this->input->post('email');
    $data = array(
      'user_id' => $user_id,
      'user_name'  => $name,
      'phone'  => $phone,
      'address'  => $address,
      'dorm'  => $dorm,
      'user_mail'  => $email,
    );
    if ($query == null)//添加新用户
    {    
      $this->db->insert('user', $data); 
    }
    else//更新用户信息
    {
      $this->db->where('user_id', $user_id);
      $this->db->update('user', $data);
    }
    return $data;
  }

  public function new_item($pic_address, $store_id)
  {
    $show_pic = $this->input->post('show_pic');
    if ($show_pic == 'show')
    {
      $show_pic = 0;
    }
    else
    {
      $show_pic = 1;
    }

    $item_price = (float)$this->input->post('item_price');
    $data = array(
      'item_name'  => $this->input->post('item_name'),
      'item_type'  => $this->input->post('item_type'),
      'item_price'  => $item_price,
      'item_note'  => $this->input->post('item_note'),
      'item_pic'  => $pic_address,
      'store_id'   => $store_id,
      'show_pic'   => $show_pic,
      'item_state'  => 1,
    );
    $this->db->insert('item', $data);
    return $this->db->insert_id();
  }

  public function delete_item($item_id, $store_id)
  {
    $data = array(
      'item_state' => 2,
    );
    $this->db->where('store_id', $store_id);
    $this->db->where('item_id', $item_id);
    return $this->db->update('item', $data);
  } 

}